package com.xincheng.shuimalong.view;

import android.content.Context;
import android.support.v7.widget.GridLayoutManager;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.AttributeSet;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.xincheng.library.xswipemenurecyclerview.adapter.BaseListRecyclerAdapter;
import com.xincheng.library.xswipemenurecyclerview.holder.RecyclerHolder;
import com.xincheng.library.xswipemenurecyclerview.listener.OnItemClickListener;
import com.xincheng.library.xswipemenurecyclerview.recycler.MRecyclerView;
import com.xincheng.shuimalong.R;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by 许浩 on 2017/7/23.
 */

public class PasswordView extends RelativeLayout {
    Context context;

    private String strPassword;     //输入的密码
    private TextView[] tvList;      //用数组保存6个TextView，为什么用数组？
    //因为就6个输入框不会变了，用数组内存申请固定空间，比List省空间（自己认为）
    private MRecyclerView gridView;    //用GrideView布局键盘，其实并不是真正的键盘，只是模拟键盘的功能
    private ArrayList<Map<String, String>> valueList;    //有人可能有疑问，为何这里不用数组了？
    //因为要用Adapter中适配，用数组不能往adapter中填充

    private int currentIndex = -1;    //用于记录当前输入密码格位置
    private OnPasswordInputCallback inputCallback;

    public PasswordView(Context context) {
        this(context, null);
    }

    public PasswordView(Context context, AttributeSet attrs) {
        super(context, attrs);
        this.context = context;
        View view = View.inflate(context, R.layout.pass_word_layout, null);

        valueList = new ArrayList<Map<String, String>>();
        tvList = new TextView[6];

        gridView = (MRecyclerView) view.findViewById(R.id.keyboard_mrv);
        gridView.setLayoutManager(new GridLayoutManager(context, 3));
        addView(view);      //必须要，不然不显示控件
    }

    public void setTvList(TextView[] tvList) {
        this.tvList = tvList;
        setView();
    }

    private void setView() {
        /* 初始化按钮上应该显示的数字 */
        for (int i = 1; i < 13; i++) {
            Map<String, String> map = new HashMap<String, String>();
            if (i < 10) {
                map.put("name", String.valueOf(i));
            } else if (i == 10) {
                map.put("name", "");
            } else if (i == 12) {
                map.put("name", "x");
            } else if (i == 11) {
                map.put("name", String.valueOf(0));
            }
            valueList.add(map);
        }

        gridView.setAdapter(new MyAdapter(context, valueList));
        gridView.setOnItemClickListener(new OnItemClickListener() {
            @Override
            public void onItemClick(RecyclerHolder holder, View view, int position) {
                if (position < 11 && position != 9) {    //点击0~9按钮
                    if (currentIndex >= -1 && currentIndex < 5) {      //判断输入位置————要小心数组越界
                        tvList[++currentIndex].setText(valueList.get(position).get("name"));
                    }
                } else {
                    if (position == 11) {      //点击退格键
                        if (currentIndex - 1 >= -1) {      //判断是否删除完毕————要小心数组越界
                            tvList[currentIndex--].setText("");
                        }
                    }
                }
            }
        });
    }

    //设置监听方法，在第6位输入完成后触发
    public void setOnFinishInput(OnPasswordInputCallback pwdInputCallback) {
        this.inputCallback = pwdInputCallback;
        tvList[5].addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                if (s.toString().length() == 1) {
                    strPassword = "";     //每次触发都要先将strPassword置空，再重新获取，避免由于输入删除再输入造成混乱
                    for (int i = 0; i < 6; i++) {
                        strPassword += tvList[i].getText().toString().trim();
                    }
                    inputCallback.inputFinish();    //接口中要实现的方法，完成密码输入完成后的响应逻辑
                }
            }
        });
    }

    /* 获取输入的密码 */
    public String getStrPassword() {
        return strPassword;
    }
    public void clearPassword(){
        this.strPassword="";
    }

    private class MyAdapter extends BaseListRecyclerAdapter<Map<String, String>, MyAdapter.ViewHolder> {

        public MyAdapter(Context context, List<Map<String, String>> dataList) {
            super(context, dataList);
        }

        @Override
        public int getViewLayoutId(int viewType) {
            return R.layout.item_gride;
        }

        @Override
        public ViewHolder createViewHolder(View itemView, int viewType) {
            return new ViewHolder(itemView);
        }

        @Override
        public void convert(ViewHolder holder, Map<String, String> map, int position) {
            holder.btnKey.setText(map.get("name"));
            if (position == 9) {
                holder.btnKey.setBackgroundResource(R.drawable.selector_key_del);
                holder.btnKey.setEnabled(false);
            }
            if (position == 11) {
                holder.btnKey.setBackgroundResource(R.drawable.selector_key_del);
            }
        }

        class ViewHolder extends RecyclerHolder {
            private TextView btnKey;

            public ViewHolder(View itemView) {
                super(itemView);
                btnKey = (TextView) itemView.findViewById(R.id.btn_keys);
            }
        }
    }

    public interface OnPasswordInputCallback {
        void inputFinish();
    }
}

